import { UseGuards, Controller, Body, Param, Get, Put, Post, Query, Req } from '@nestjs/common'
import { ExampleService } from './example.service'
import { ApiTags, ApiOperation, ApiQuery, ApiParam, ApiBody, ApiBearerAuth } from '@nestjs/swagger'
import { AuthGuard } from '@nestjs/passport'
import { Auth } from '../roles.decorator'
import { UserDto, FindUpdateDto } from './dto'

@Controller('example')
@ApiTags('示例')
export class ExampleController {
  constructor(private readonly exapleService: ExampleService) {}

  @Get()
  @ApiOperation({ summary: '取所有数据' })
  @Auth('user-data', 'read')
  getHello(): Promise<UserDto[]> {
    return this.exapleService.getAllData()
  }

  @Post('add')
  @ApiOperation({ summary: '添加' })
  @ApiBody({ type: UserDto, description: '用户dto', required: true })
  createDate(@Body() wxUser: UserDto) {
    return this.exapleService.createDate(wxUser)
  }

  @Get('datele')
  @ApiOperation({ summary: '删除' })
  @ApiQuery({
    name: 'username',
    description: '要删除数据的用户名',
    required: true,
  })
  deleteDate(@Query('username') name: string) {
    return this.exapleService.daleteDate(name)
  }

  @Post('update')
  @ApiOperation({ summary: '更新' })
  @ApiBody({ type: FindUpdateDto, description: 'findDto', required: true })
  @ApiBearerAuth()
  @UseGuards(AuthGuard('jwt'))
  updateDate(@Body() findUpdate: FindUpdateDto, @Req() req: any) {
    const newData = {
      password: findUpdate.password,
      jobs: findUpdate.jobs,
    }
    const { id } = req.user
    return this.exapleService.updateDate(id, newData)
  }

  @Get('query')
  @ApiOperation({ summary: '查询' })
  @ApiQuery({ name: 'username', description: '模糊查询', required: true })
  queryDate(@Query('username') username: string) {
    return this.exapleService.findDate(username)
  }

  @Put('edit/:id')
  @ApiOperation({ summary: '更新 - restful示例' })
  @ApiParam({ name: 'id', description: '操作的id', required: true })
  putData(@Param() params, @Body() userDto: UserDto) {
    const newData = {
      username: userDto.username,
      password: userDto.password,
      jobs: userDto.jobs,
    }
    return this.exapleService.updateDate(params.id, newData)
  }
}
